package com.wdb007.venus.web.api.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.wdb.exchange.model.WxUserRelationRpcModel;
import com.wdb007.venus.svc.facade.UserService;
import com.wdb007.venus.svc.facade.WxAPPMessagePushService;
import com.wdb007.venus.svc.facade.WxAppHDService;
import com.wdb007.venus.svc.facade.constant.BizConstants;
import com.wdb007.venus.svc.facade.constant.RspCodeEnum;
import com.wdb007.venus.svc.facade.exception.BizException;
import com.wdb007.venus.svc.facade.wxapp.model.MutilReadRecordDTO;
import com.wdb007.venus.svc.facade.wxapp.model.SendMsgReqDTO;
import com.wdb007.venus.svc.facade.wxapp.model.SingleReadRecordDTO;
import com.wdb007.venus.web.api.model.BaseResponse;
import com.wdb007.venus.web.api.wxapp.model.PresentAmountRequest;
import com.wdb007.venus.web.api.wxapp.model.PresentVIPRequest;
import com.wdb007.venus.web.api.wxapp.model.WxAppMultiUserReadRecordResponse;
import com.wdb007.venus.web.api.wxapp.model.WxAppUserReadRecordResponse;

@Controller
@RequestMapping("/wxapp/")
public class WxappController extends BaseController{

	private final static Logger logger = LoggerFactory.getLogger(WxappController.class);
	
	@Autowired
	private WxAPPMessagePushService wxAPPMessagePushService;
	@Autowired
	private WxAppHDService wxAppHDService;
	@Autowired
	private UserService userService ;
	
	/**
	 * 微信小程序消息模板发送接口
	 * @param httpRequest
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/templateMessage", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse templateMessage(HttpServletRequest request){
		BaseResponse baseResponse = success();
		SendMsgReqDTO dto = new SendMsgReqDTO();
		dto.setForm_id(request.getParameter("form_id"));
		dto.setTemplate_id(request.getParameter("template_id"));
		dto.setTouser(request.getParameter("openid"));
		
		//TODO 测试用，实际发送在后端设置具体内容
		Map<String, Object> data = new HashMap<>();
		Map<String, Object> keyword1 = new HashMap<>();
		keyword1.put("value", "2018年1月15日");
		keyword1.put("color", "#113177");
		data.put("keyword1", keyword1);
		
		Map<String, Object> keyword2 = new HashMap<>();
		keyword2.put("value", "keyword2");
		keyword2.put("color", "#123172");
		data.put("keyword2", keyword2);
		
		Map<String, Object> keyword3 = new HashMap<>();
		keyword3.put("value", "keyword3");
		keyword3.put("color", "#133173");
		data.put("keyword3", keyword3);
		
		Map<String, Object> keyword4 = new HashMap<>();
		keyword4.put("value", "keyword4");
		keyword4.put("color", "#143174");
		data.put("keyword4", keyword4);
		
		Map<String, Object> keyword5 = new HashMap<>();
		keyword5.put("value", "keyword5");
		keyword5.put("color", "#153175");
		data.put("keyword5", keyword5);
		
		dto.setData(data);
		String result = wxAPPMessagePushService.sendTemplateMsg(dto);
		
		baseResponse.setDetail(result);
		
		return baseResponse;
	}

	/**
	 * 小程序formid存储
	 */
	@RequestMapping(value="/saveMsgFormId", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse saveMsgFormId(HttpServletRequest request){
		BaseResponse baseResponse = success();
		String appid = request.getParameter("appid");
		String useridStr = request.getParameter("userid");
		String usertoken = request.getHeader("token");
		Long userid = null;
		Map<String, Object> wxUserInfoMap = null;
		//根据userid查找对应的微信信息
		if(isEmpty(useridStr)) {
			wxUserInfoMap = userService.getWxUserinfoByTokenV2(usertoken, null, null);
		}else {
			userid = Long.valueOf(useridStr);
			wxUserInfoMap = userService.getWxUserinfoByTokenV2(null, userid, appid);
		}
		//查询对应的openid和appid
		String openid = null;
		if(isEmpty(wxUserInfoMap.get("wxUserRelation"))) {
			try {
				checkIsNull(openid, "未查到对应的微信信息");
			} catch (BizException e) {
				e.printStackTrace();
			}
		}else {
			WxUserRelationRpcModel wxUserInfo = (WxUserRelationRpcModel) wxUserInfoMap.get("wxUserRelation");
			openid = wxUserInfo.getOpenid();
		}
		//查询对应的openid和appid
		String formId = request.getParameter("formId");
		
		logger.info("saveFormId: userId:{},openid:{},formId:{}",userid, openid, formId);
		wxAPPMessagePushService.saveMsgFormId(appid, openid, userid, formId);
		return baseResponse;
	}
	
	@RequestMapping(value="/getUserRecord", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getUserRecord(Long userid){
		logger.info("getUserRecord's userid: {}", userid);
		BaseResponse baseResponse = success();
		try{
			checkIsNull(userid, "userid");
			SingleReadRecordDTO singleUserReadRecord = wxAppHDService.getSingleUserReadRecord(userid);
			WxAppUserReadRecordResponse response = new WxAppUserReadRecordResponse();
			BeanUtils.copyProperties(singleUserReadRecord, response);
			baseResponse.setDetail(response);
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("getUserRecord's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}
	
	@RequestMapping(value="/getUserRecords", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getUserRecords(){
		BaseResponse baseResponse = success();
		try{
			List<MutilReadRecordDTO> list = wxAppHDService.getMutliUserReadRecord();
			if(!list.isEmpty()){
				List<WxAppMultiUserReadRecordResponse> items = new ArrayList<WxAppMultiUserReadRecordResponse>(list.size());
				for(MutilReadRecordDTO rr : list){
					WxAppMultiUserReadRecordResponse mutilResponse = new WxAppMultiUserReadRecordResponse();
					mutilResponse.setUserid(rr.getUserid());
					WxAppUserReadRecordResponse single = new WxAppUserReadRecordResponse();
					BeanUtils.copyProperties(rr.getRecord(), single);
					mutilResponse.setRecord(single);
					items.add(mutilResponse);
				}
				baseResponse.setItems(items);
			}
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("getUserRecord's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}
	
	@RequestMapping(value="/presentVIP", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse presentVIP(PresentVIPRequest request){
		logger.info("presentVIP's request: {}", request);
		BaseResponse baseResponse = success();
		
		try{
			checkIsNull(request.getMobile_no(), "mobile_no");
			checkIsNull(request.getVip_type(), "vip_type");
			wxAppHDService.presentVIP(request.getMobile_no(), request.getVip_type());
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("presentVIP's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}
	
	@RequestMapping(value="/presentAmount", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse presentAmount(PresentAmountRequest request){
		logger.info("presentAmount's request: {}", request);
		BaseResponse baseResponse = success();
		
		try{
			checkIsNull(request.getMobile_no(), "mobile_no");
			checkIsNull(request.getAmount(), "amount");
			wxAppHDService.presentAmount(request.getMobile_no(), request.getAmount());
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		logger.info("presentAmount's response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}

	//根据unionid查询对应的用户信息
	@RequestMapping(value="/getUserInfoByUnionids", method=RequestMethod.POST)
	@ResponseBody
	public BaseResponse getUserInfoByUnionids(HttpServletRequest request) {
		logger.info("getUserInfoByUnionids request: {}", request);
		//根据unionid查询对应的用户信息，并返回头像昵称
		BaseResponse baseResponse = success();
		
		baseResponse.setDetail(userService.getUserinfoByUnionids(request.getParameter("unionids")));
		logger.info("getUserInfoByUnionids response: {}", JSON.toJSONString(baseResponse));
		return baseResponse;
	}
	
	//根据usertoken查询对应的用户信息
	@RequestMapping(value="/getWxUserinfoByToken", method=RequestMethod.GET)
	@ResponseBody
	public BaseResponse getWxUserinfoByToken(HttpServletRequest request) {
		String usertoken = request.getParameter("usertoken");
		String userIdStr = request.getParameter("userid");
		String appId = request.getParameter("appid");
		BaseResponse baseResponse = success();
		try {
			checkIsNull(appId, "appid");
			checkIsNull(usertoken, "usertoken");
			Long userId = null;
			if(!isEmpty(userIdStr)) {
				userId = Long.valueOf(userIdStr);
			}
			//存在userid判断token是否过期
			if(!isEmpty(userId)) {
				String checktoken = userService.getTokenByChannelAndUserId(userId, BizConstants.CHANNEL_WX);
				if(!usertoken.equals(checktoken)) {
					throw new BizException(RspCodeEnum.USER_TOKEN_IS_UNVALID);
				}
			}
			
			baseResponse.setDetail(userService.getWxUserinfoByTokenV2(usertoken, userId, appId));
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
			baseResponse = failed(e);
		}
		
		return baseResponse;
	}
}
